package com.swe727.spring2011.constraint1.server;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import com.swe727.spring2011.constraint1.client.NodeController;
import com.swe727.spring2011.constraint1.node.NodeDataStore;
import com.swe727.spring2011.constraint1.observation.ObservationDataStore;

public class ZoneServer {

	public static final String SAVE_OBSERVATION_ID = "saveObservation";
	public static final String GET_OBSERVATION_ID = "getObservation";
	public static final String REGISTER_ID = "register";
	public static final String MEDEVAC_ID = "medevac";
	public static String LOGFILE;
	
	public static void main(String[] args) throws NumberFormatException, RemoteException {
		if (args.length !=2) {
			System.out.println("Usage: ZoneServer <port>\nwhere port is the port number of the RMI registry.<id>for log file");
			System.exit(1);
		}
		
		System.out.println("ZoneServer running on port "+args[0]+". May the force be with you.....");
		LOGFILE="Server."+args[1]+".log";
		
		Registry registry = LocateRegistry.createRegistry(Integer.parseInt(args[0]));
		
		// initialize the data stores
		ObservationDataStore obsStore = ObservationDataStore.getStore();
		NodeDataStore.getStore();
		
		SaveObservationHandler saveObs = new SaveObservationHandler(obsStore,LOGFILE);
		GetObservationHandler getObs = new GetObservationHandler(obsStore);
		RegisterNodeHandler regNode = new RegisterNodeHandler();
		ServerMedevacHandler med = new ServerMedevacHandler();
		
		SaveObservationRemote saveObsStub = (SaveObservationRemote) UnicastRemoteObject.exportObject(saveObs, 0);
		GetObservationRemote getObsStub = (GetObservationRemote) UnicastRemoteObject.exportObject(getObs, 0);
		RegisterNodeRemote regNodeStub = (RegisterNodeRemote) UnicastRemoteObject.exportObject(regNode, 0);
		ServerMedevacRemote medStub = (ServerMedevacRemote) UnicastRemoteObject.exportObject(med, 0);
		
        registry.rebind(SAVE_OBSERVATION_ID, saveObsStub);
        registry.rebind(GET_OBSERVATION_ID, getObsStub);
        registry.rebind(REGISTER_ID, regNodeStub);
        registry.rebind(MEDEVAC_ID, medStub);
        
        while (true) {
        	
        }
	}
	private static void WriteLog(String msg) {
		
		try
		{
			FileOutputStream fos = new FileOutputStream(LOGFILE, true);
			
			fos.write(msg.getBytes());
			
			fos.close();
		}
		catch(FileNotFoundException ex)
		{
			System.out.println("FileNotFoundException : " + ex);
		}
		catch(IOException ioe)
		{
			System.out.println("IOException : " + ioe);
		}
	}

}
